﻿#include "RecordTableModel.h"

RecordTableModel::RecordTableModel(QObject *parent)
    : QAbstractTableModel(parent)
{
}

void RecordTableModel::setJsonData(const QJsonValue &jsonData)
{
    beginResetModel();
    m_dataArray = jsonData.toArray();

    if (!m_dataArray.isEmpty() && m_dataArray[0].isObject()) {
        m_headers = m_dataArray[0].toObject().keys();
    }

    m_currentPage = 0;
    endResetModel();
}
void RecordTableModel::addRecord(const QJsonObject &newRecord)
{
    beginInsertRows(QModelIndex(), 0, 0);
    m_dataArray.prepend(newRecord);
    endInsertRows();
}
int RecordTableModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (m_dataArray.isEmpty()) return 0;
    int start = m_currentPage * m_pageSize;
    return qMax(0, qMin(m_pageSize, m_dataArray.size() - start));
}

int RecordTableModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_headers.size();
}

QVariant RecordTableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= rowCount() || index.column() >= m_headers.size())
        return QVariant();

    int dataIndex = m_currentPage * m_pageSize + index.row();
    if (dataIndex >= m_dataArray.size()) return QVariant();

    if (role == Qt::DisplayRole) {
        QJsonObject obj = m_dataArray[dataIndex].toObject();
        return obj.value(m_headers[index.column()]).toVariant();
    }

    return QVariant();
}

QVariant RecordTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DisplayRole) {
        if (orientation == Qt::Horizontal) {
            return m_headers.value(section);
        } else {
            return section + 1;
        }
    }
    return QVariant();
}

void RecordTableModel::setPageSize(int pageSize)
{
    m_pageSize = pageSize;
    firstPage();
}

void RecordTableModel::firstPage()
{
    beginResetModel();
    m_currentPage = 0;
    endResetModel();
}

void RecordTableModel::prevPage()
{
    if (m_currentPage > 0) {
        beginResetModel();
        --m_currentPage;
        endResetModel();
    }
}

void RecordTableModel::nextPage()
{
    if ((m_currentPage + 1) * m_pageSize < m_dataArray.size()) {
        beginResetModel();
        ++m_currentPage;
        endResetModel();
    }
}

void RecordTableModel::lastPage()
{
    beginResetModel();
    m_currentPage = (m_dataArray.size() - 1) / m_pageSize;
    endResetModel();
}

void RecordTableModel::goToPage(int page)
{
    if (page >= 0 && page < totalPages()) {
        beginResetModel();
        m_currentPage = page;
        endResetModel();
    }
}

int RecordTableModel::currentPage() const
{
    return m_currentPage;
}

int RecordTableModel::totalPages() const
{
    return (m_dataArray.size() + m_pageSize - 1) / m_pageSize;
}
